import { createI18n } from 'vue-i18n'
import { Locale } from 'vant'
import Store from '@/store'
// 引入公共国际化语言，文件单独的则单独引入
import EN from './en_US'
import zh_CN from './zh-CN'
// elementui国际化
import enLocale from 'vant/es/locale/lang/en-US'
import zhLocale from 'vant/es/locale/lang/zh-CN'
import { getUrlLang } from '../libs/utils/locale'

const messages = {
  'en-US': {
    ...EN,
    ...enLocale
  },
  'zh-CN': {
    ...zh_CN,
    ...zhLocale
  }
}
export const urlLang = getUrlLang()
export const defaultLang = urlLang || (Store?.state?.locale?.localeLang || 'zh-CN')
Store.dispatch('locale/setLocalLang', defaultLang)
console.log('defaultLang', defaultLang)

Locale.use(defaultLang, messages[defaultLang])

const i18n = createI18n({
  locale: defaultLang,
  fallbackLocale: 'zh-CN',
  silentTranslationWarn: true,
  messages
})

const t = i18n?.global?.t
if (window) window.$t = (key, value) => t(key, value)

const keywordsId = document.getElementById('metaKeywords')
const descriptionId = document.getElementById('metaDescription')

export const changeLocale = (meta) => {
  if (meta?.title) {
    document.title = meta.title
  }
  if (meta?.i18nTitle) {
    document.title = t(meta.i18nTitle)
  }
  if (meta?.keyWords) {
    keywordsId.content = meta.keyWords
  }
  if (meta?.i18nKeywords) {
    keywordsId.content = t(meta.i18nKeywords)
  }
  if (meta?.description) {
    descriptionId.content = meta.description
  }
  if (meta?.i18nDescription) {
    descriptionId.content = t(meta.i18nDescription)
  }
}

export default i18n
